package com.iscc.fake.dao.Impl;

import com.iscc.fake.dao.CommentDAO;
import com.iscc.fake.domain.Comment;
import com.iscc.fake.domain.Pager;
import com.iscc.fake.util.DataSourceUtile;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class CommentDaoImpl  implements CommentDAO {
    @Override
    public int selectCount() {
        int result = 0;
        String sql="SELECT count(*) FROM coomment";
        Connection conn= null;
        PreparedStatement ps=null;
        ResultSet rs=null;
        try {
            conn = DataSourceUtile.getConnection();

            //预处理对象
            ps =conn.prepareStatement(sql);

            //执行SQL语句
            rs = ps.executeQuery();
            if (rs.next()) {
                result = rs.getInt(1);
            }

        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            DataSourceUtile.closeReource(rs,ps,conn);
        }

        return result;

    }


    //查询评价
    @Override
    public List<Comment> selectComment(Pager pager) {

        List<Comment> list=new ArrayList<>();
        String sql="SELECT * from coomment limit ? , ?";
        Connection conn= null;
        PreparedStatement ps=null;
        ResultSet rs=null;
        try {
            conn = DataSourceUtile.getConnection();

            //预处理对象
            ps =conn.prepareStatement(sql);
            ps.setInt(1,pager.getStart());
            ps.setInt(2,pager.getPageNum());

            //执行SQL语句
            rs = ps.executeQuery();
            while (rs.next()) {
                Comment comment = new Comment();

               comment.setComno(rs.getInt(1));
               comment.setCtext(rs.getString(2));
               comment.setUno(rs.getInt(3));
               comment.setStar(rs.getInt(4));
               comment.setPno(rs.getInt(5));
               list.add(comment);

            }

        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            DataSourceUtile.closeReource(rs,ps,conn);
        }

        return list;
    }



    //增加评价
    @Override
    public int addComment(Comment comment) {
        String sql = "INSERT INTO coomment(ctext,uno,star,pno) VALUES(?,?,?,?)";
        int result = -1;
        Connection conn=null;
        PreparedStatement psmt=null;
        ResultSet rs=null;
        try {
            conn = DataSourceUtile.getConnection();
            psmt = conn.prepareStatement(sql);

            psmt.setString(1,comment.getCtext());
            psmt.setInt(2,comment.getUno());
            psmt.setInt(3,comment.getStar());
            psmt.setInt(4,comment.getPno());
            result = psmt.executeUpdate();

        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            DataSourceUtile.closeReource(psmt,conn);
        }

        return result;
    }

}
